package cn.mymall.web.interceptor;

import cn.mymall.constant.EMallConstant;
import cn.mymall.constant.ResultCodeConstant;
import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.User;
import cn.mymall.redis.RedisHelper;
import cn.mymall.service.IUserService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.FastJsonUtil;
import cn.mymall.vo.user.UserResVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HoutaiInterceptor implements HandlerInterceptor {
    private Logger dbLogger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisHelper redisHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuid = BaseWebUtil.getHeaderMap(request).get("uuid");
        if(StringUtils.isBlank(uuid)){
            responseMsg(ResultCodeConstant.RE_LOGIN, response);
            return  false;
        }
        Integer userId = (Integer) redisHelper.get(uuid);
        if(userId==null){
            responseMsg(ResultCodeConstant.RE_LOGIN, response);
            return  false;
        }
        User user = userService.getById(userId);
        if(!StringUtils.equalsIgnoreCase(user.getStatus(), StatusConstant.Y)){
            responseMsg(ResultCodeConstant.LOGIN_AUTH_INVILID, response);
            return  false;
        }
        UserResVo userVo = new UserResVo();
        userVo.setId(user.getId());
        userVo.setMobile(user.getMobile());
        userVo.setUsername(user.getUsername());
        request.setAttribute(EMallConstant.REQUEST_LOGIN_USER,  userVo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    private void responseMsg(ResultCodeConstant codeConstant, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json; charset=utf-8");
        writer.write(FastJsonUtil.toJsonString(ResultCode.getFailure(codeConstant.getCode(),codeConstant.getMessage())));
        writer.flush();
        writer.close();
    }
}
